import 'package:flutter/foundation.dart';
import 'package:homepad/iot/message_def.dart';
import 'package:homepad/logger/logger.dart';
import 'package:homepad/iot/basic_node.dart';
import 'package:homepad/iot/nova_config.dart';
import 'websocket_client.dart';

class NovaModel extends ChangeNotifier implements WebsocketDelegate, BasicNodeDelegate {
  final NovaConfig config;
  NovaModel({required this.config}) {
    for (var node in config.nodes) {
      node.delegate = this;
    }
    logger.info("config.location: ${config.location}");
  }

  late WebsocketClient _client;
  @override
  void dispose() {
    super.dispose();
    _client.close();
  }
  WebsocketClient get client => _client;

  set client(WebsocketClient client) {
    _client = client;
      // 获取状态数据
    notifyListeners();
    _client.start(config.remoteUrl);
  }

  @override
  void onAttributeReport(AttributeDataIB report) {
    for (var node in config.nodes) {
      if (node.endpointId == report.path.endpoint) {
        if (node.onAttributeReport(report.path, report.data)) {
          notifyListeners();
        }
      }
    }
  }

  @override
  void onWebsocketStateChanged(WebsocketState state) {
    logger.info("websocket_state: $state");
    notifyListeners();
    if (state == WebsocketState.established) {
      for (var node in config.nodes) {
        node.readAllState();
      }
    }
  }

  @override
  void onStateChanged(String state) {
    logger.info("node_state: $state");
    notifyListeners();
  }

  @override
  void onAttributeSet(AttributePathIB path, dynamic data) {
    client.writeRequest(AttributeDataIB(path: path, data: data));
    // notifyListeners();
  }

  @override
  void onAttributeGet(AttributePathIB path) {
    client.readRequest(path);
  }


}
